package com.yn.sample.execution.objectfactory;

import com.yn.sample.CheckAndSet;
import com.yn.sample.execution.memory.MemoryManagement;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

import java.lang.reflect.Field;
import java.util.List;

public class CustomObjectFactory {

    public static Object newObject(Class<?> clazz) {
        /**
         * 1 获取classinfo，里面包括了该类对象要占用的空间大小、field的offset信息
         */
        ClassInfo classInfo = ClassIntrospectorUtil.getByClass(clazz);

        /**
         * 2 new一个对象出来，在内存中分配对应的空间
         */
        CustomObject customObject = new CustomObject(classInfo);

        /**
         * 3 创建对象的代理，代理其所有方法
         */
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setProxyTargetClass(true);
        proxyFactory.setTargetClass(clazz);

        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        MethodInterceptorForCustomObject interceptor = new MethodInterceptorForCustomObject(customObject);
        advisor.setAdvice(interceptor);

        proxyFactory.addAdvisor(advisor);


        return proxyFactory.getProxy();
    }

    public static void main(String[] args) {
        CheckAndSet o = (CheckAndSet) newObject(CheckAndSet.class);
        o.setF(444);
        int f = o.getF();
        System.out.println("field value: " + f);
    }
}
